//
//  XinLvTestViewController.m
//  安好
//
//  Created by qinlongqing on 14-8-26.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//

#import "XinLvTestViewController.h"
#import "XinLvTestingViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "Reachability.h"
#import "CLDataBaseController.h"





#import "XinLvTestResultViewController.h"





@interface XinLvTestViewController ()<UITextFieldDelegate>
{
    
    NSMutableDictionary *testResult;
    
    UIView *enterNameView;
    
    UIView *inputUserNameView;
    
    XinLvTestingViewController *xinLvTestingViewController;
    
    NSTimer *timer;
    
    CGFloat touxiangImageViewHeight;
    CGFloat label1Height;
    CGFloat label2Height;
    CGFloat startBTNHeight;
}
@end

@implementation XinLvTestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self makeNavBar];
    
    testResult = [[NSMutableDictionary alloc]init];

    self.navigationItem.title = @"心率";
    [self.view setBackgroundColor:UIColorFromRGB(0x4fc1e9)];
    
    if (kScreenWidth == 414) {
        touxiangImageViewHeight = 240;
        label1Height = 24;
        label2Height = 24;
        startBTNHeight = 54;
    }
    else{
        touxiangImageViewHeight = 200;
        label1Height = 20;
        label2Height = 20;
        startBTNHeight = 45;
    }
    CGFloat space = (kScreenHeight - 64 - touxiangImageViewHeight - label1Height - label2Height - startBTNHeight)/4;
    
    UIImageView *touxiangImageView = [[UIImageView alloc]init];
    touxiangImageView.frame = CGRectMake((kScreenWidth - touxiangImageViewHeight)/2, space, touxiangImageViewHeight, touxiangImageViewHeight);
    touxiangImageView.image = [UIImage imageNamed:@"xin_lv_start"];
    [self.view addSubview:touxiangImageView];
    
    UILabel *label1 = [[UILabel alloc]init];
    label1.frame = CGRectMake(0, touxiangImageView.frame.origin.y + touxiangImageView.frame.size.height + space, kScreenWidth, label1Height);
    if (kScreenWidth == 414) {
        label1.font = [UIFont boldSystemFontOfSize:17];
    }
    else{
        label1.font = [UIFont boldSystemFontOfSize:15];
    }
    label1.text = @"测试过程中请勿移动手指,请用左手食指指腹";
    label1.textColor = [UIColor whiteColor];
    label1.textAlignment = NSTextAlignmentCenter;
    label1.backgroundColor = [UIColor clearColor];
    [self.view addSubview:label1];
    
    UILabel *label2 = [[UILabel alloc]init];
    label2.frame = CGRectMake(0, label1.frame.origin.y + label1.frame.size.height + 10, kScreenWidth, label2Height);
    if (kScreenWidth == 414) {
        label2.font = [UIFont boldSystemFontOfSize:17];
    }
    else{
        label2.font = [UIFont boldSystemFontOfSize:15];
    }
    label2.text = @"完全遮住摄像头与闪光灯,测试会自动开始";
    label2.textColor = [UIColor whiteColor];
    label2.textAlignment = NSTextAlignmentCenter;
    label2.backgroundColor = [UIColor clearColor];
    [self.view addSubview:label2];

    UIButton *startBTN = [[UIButton alloc]init];
    startBTN.layer.cornerRadius = 3;
    if (kScreenWidth == 414) {
        startBTN.frame = CGRectMake(20, label2.frame.origin.y + label2.frame.size.height + space, kScreenWidth - 40, startBTNHeight);
        startBTN.titleLabel.font = [UIFont systemFontOfSize:22];
    }
    else{
        startBTN.frame = CGRectMake(15, label2.frame.origin.y + label2.frame.size.height + space, kScreenWidth - 30, startBTNHeight);
        startBTN.titleLabel.font = [UIFont systemFontOfSize:20];
    }
    startBTN.backgroundColor = [UIColor whiteColor];
    [startBTN setTitleColor:UIColorFromRGB(0x4fc1e9) forState:UIControlStateNormal];
    [startBTN setTitle:@"开始" forState:UIControlStateNormal];
    [startBTN addTarget:self action:@selector(startTest) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBTN];
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)makeNavBar{
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(doBack)];
    [backBtnImg setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}

-(void)doBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)startTest{
//    XinLvTestResultViewController *view = [[XinLvTestResultViewController alloc]init];
//    [self.navigationController pushViewController:view animated:YES];
    
    if (kScreenHeight == 480) {
        xinLvTestingViewController = [[XinLvTestingViewController alloc]initWithNibName:@"XinLvTestingViewController" bundle:nil];
    }
    else if (kScreenHeight == 568){
        xinLvTestingViewController = [[XinLvTestingViewController alloc]initWithNibName:@"XinLvTestingViewController_5" bundle:nil];
    }
    else if (kScreenHeight == 667){
        xinLvTestingViewController = [[XinLvTestingViewController alloc]initWithNibName:@"XinLvTestingViewController_6" bundle:nil];
    }
    else if (kScreenHeight == 736){
        xinLvTestingViewController = [[XinLvTestingViewController alloc]initWithNibName:@"XinLvTestingViewController_6+" bundle:nil];
    }
    xinLvTestingViewController.xinLvTestViewController = self;
    [self.navigationController pushViewController:xinLvTestingViewController animated:YES];
}

#pragma 测试完以后显示测试报告之前
- (void)xinLvTestFinishedWithResult:(NSDictionary *)xinLvTestResult{
    testResult = [xinLvTestResult mutableCopy];
    [self loadTestResult];
}

- (void)loadTestResult{
    [self.navigationController popViewControllerAnimated:NO];
    
    //判断是否登录,如果已登录：直接存入服务器。如果未登录：存入本地
    if ([[NSString stringWithFormat:@"%@",[[UserManager shareInstance] getUserIsLogin]] length] != 0) {//已登录
        NSString *userName = [[UserManager shareInstance] getUserInfo].username;
        [testResult setValue:userName forKey:@"testUserName"];
        
        //1.有网  2.没网
        if ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {//没网
            [self createInputTestUserNameView];
        }
        else{//有网
            [self showActionView];
            NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"heartrate":[NSString stringWithFormat:@"%ld",[[testResult valueForKey:kXinLvTestResult] integerValue]]};
            [[AFHTTPRequestOperationManager manager] POST:[NSString stringWithFormat:@"%@%@",kBaseURL,kUploadXinLvTestDataURL] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSNumber * statusNum = [responseObject objectForKey:@"status"];
                NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
                NSString * statusString = [numberFormatter stringFromNumber:statusNum];
                if ([statusString isEqualToString:@"0"]) {
                    alertContent([responseObject objectForKey:@"msg"]);
                }else{
                    [self doShowTestResultView];
                }
                [self hiddenActionView];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [self createInputTestUserNameView];
                [self hiddenActionView];
            }];
        }
    }
    else{
        [self createInputTestUserNameView];
    }
}

- (void)doShowTestResultView{
    XinLvTestResultViewController *xinLvTestResultViewController = [[XinLvTestResultViewController alloc]init];
    xinLvTestResultViewController.testResultDict = testResult;
    [self.navigationController pushViewController:xinLvTestResultViewController animated:YES];
}

- (void)createInputTestUserNameView{
    enterNameView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    enterNameView.backgroundColor = [UIColor whiteColor];
    enterNameView.alpha = 0.9;
    [self.view addSubview:enterNameView];
    
    inputUserNameView = [[UIView alloc]init];
    if (IPHONE5_OR_LATER) {
        inputUserNameView.frame = CGRectMake((kScreenWidth - 290)/2, self.view.frame.size.height - 220 - 144, 290, 144);
    }
    else{
        inputUserNameView.frame = CGRectMake((kScreenWidth - 290)/2, self.view.frame.size.height - 200 - 144, 290, 144);
    }
    inputUserNameView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:inputUserNameView];
    
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 290, 144)];
    bgImageView.image = [UIImage imageNamed:@"tijian_inputImageView"];
    [inputUserNameView addSubview:bgImageView];
    
    UILabel *bgLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 31, 290, 20)];
    bgLabel.textAlignment = NSTextAlignmentCenter;
    bgLabel.textColor = UIColorFromRGB(0x4fc1e9);
    bgLabel.text = @"输入你的名号";
    bgLabel.backgroundColor = [UIColor clearColor];
    [inputUserNameView addSubview:bgLabel];
    
    UIImageView *inputBg = [[UIImageView alloc]initWithFrame:CGRectMake(22, 63, 246, 40)];
    inputBg.image = [UIImage imageNamed:@"tijianjilu_inputFieldBg"];
    [inputUserNameView addSubview:inputBg];
    
    UITextField *inputField = [[UITextField alloc]initWithFrame:CGRectMake(25, 63, 240, 40)];
    inputField.borderStyle = UITextBorderStyleNone;
    inputField.backgroundColor = [UIColor clearColor];
    inputField.adjustsFontSizeToFitWidth = YES;
    inputField.keyboardType = UIKeyboardTypeDefault;
    inputField.returnKeyType = UIReturnKeyDone;
    inputField.delegate = self;
    [inputField becomeFirstResponder];
    [inputUserNameView addSubview:inputField];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    CGRect rect = inputUserNameView.frame;
    rect.origin.y = rect.origin.y - 50;
    [UIView animateWithDuration:0.4f animations:^{
        inputUserNameView.frame = rect;
    }];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString *realText = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (realText && realText.length > 0)
    {
        //***获取字符串
        NSString *str=textField.text;
        //***调用关键方法，获得bool值，yes或者no：
        BOOL ok= [self isIncludeSpecialCharact:str];
        if (ok==YES) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"搜索不能为特殊字符!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
        else{
            [testResult setValue:realText forKey:@"testUserName"];

#pragma  记录到数据库
            [[CLDataBaseController instance] insertTableWithTestType:xinLvTest andDict:testResult];
            
            CGRect rect = inputUserNameView.frame;
            rect.origin.y = rect.origin.y + 50;
            [UIView animateWithDuration:0.4f animations:^{
                inputUserNameView.frame = rect;
                inputUserNameView.alpha = 0;
                enterNameView.alpha = 0;
            } completion:^(BOOL finished) {
                [self doShowTestResultView];
            }];
            
            [textField resignFirstResponder];
            return YES;
        }
        //***关键方法
    }
    else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"搜索内容不能为空!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    return YES;
}

-(BOOL)isIncludeSpecialCharact: (NSString *)str
{
    //***需要过滤的特殊字符：~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€。
    NSRange urgentRange = [str rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString: @"~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€"]];
    if (urgentRange.location == NSNotFound){
        return NO;
    }
    return YES;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
